"""
设备数据模型
"""

from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional, List


class DeviceStatus(str, Enum):
    """设备状态枚举"""
    ONLINE = "online"
    OFFLINE = "offline"
    NETWORK_ISSUE = "network_issue"
    SERVICE_ISSUE = "service_issue"
    UNKNOWN = "unknown"


@dataclass
class DeviceInfo:
    """设备基本信息"""
    device_id: str
    ip_address: str
    endpoint_url: str
    manufacturer: str = ""
    model: str = ""
    serial_number: str = ""
    mac_address: str = ""
    port: int = 80
    status: DeviceStatus = DeviceStatus.UNKNOWN
    first_discovered: Optional[datetime] = None
    last_seen: Optional[datetime] = None
    
    def __post_init__(self):
        """初始化后处理"""
        if self.first_discovered is None:
            self.first_discovered = datetime.now()
        if self.last_seen is None:
            self.last_seen = datetime.now()
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'device_id': self.device_id,
            'ip_address': self.ip_address,
            'endpoint_url': self.endpoint_url,
            'manufacturer': self.manufacturer,
            'model': self.model,
            'serial_number': self.serial_number,
            'mac_address': self.mac_address,
            'port': self.port,
            'status': self.status.value,
            'first_discovered': self.first_discovered.isoformat() if self.first_discovered else None,
            'last_seen': self.last_seen.isoformat() if self.last_seen else None
        }
    
    @classmethod
    def from_dict(cls, data: dict) -> 'DeviceInfo':
        """从字典创建对象"""
        device = cls(
            device_id=data['device_id'],
            ip_address=data['ip_address'],
            endpoint_url=data['endpoint_url'],
            manufacturer=data.get('manufacturer', ''),
            model=data.get('model', ''),
            serial_number=data.get('serial_number', ''),
            mac_address=data.get('mac_address', ''),
            port=data.get('port', 80),
            status=DeviceStatus(data.get('status', DeviceStatus.UNKNOWN))
        )
        
        # 处理时间字段
        if data.get('first_discovered'):
            device.first_discovered = datetime.fromisoformat(data['first_discovered'])
        if data.get('last_seen'):
            device.last_seen = datetime.fromisoformat(data['last_seen'])
            
        return device


@dataclass
class NetworkMetrics:
    """网络性能指标"""
    latency_ms: float
    packet_loss_rate: float
    jitter_ms: float = 0.0
    timestamp: Optional[datetime] = None
    
    def __post_init__(self):
        """初始化后处理"""
        if self.timestamp is None:
            self.timestamp = datetime.now()
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'latency_ms': self.latency_ms,
            'packet_loss_rate': self.packet_loss_rate,
            'jitter_ms': self.jitter_ms,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }


@dataclass
class DeviceStatusRecord:
    """设备状态记录"""
    device_id: str
    status: DeviceStatus
    network_metrics: Optional[NetworkMetrics] = None
    open_ports: List[int] = None
    error_message: str = ""
    timestamp: Optional[datetime] = None
    
    def __post_init__(self):
        """初始化后处理"""
        if self.timestamp is None:
            self.timestamp = datetime.now()
        if self.open_ports is None:
            self.open_ports = []
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'device_id': self.device_id,
            'status': self.status.value,
            'network_metrics': self.network_metrics.to_dict() if self.network_metrics else None,
            'open_ports': self.open_ports,
            'error_message': self.error_message,
            'timestamp': self.timestamp.isoformat() if self.timestamp else None
        }
